package odnoklassniki;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import musictrackrecommendation.DatabaseDataset;
import musictrackrecommendation.Dataset;
import musictrackrecommendation.ExperimentParameters;

import randomwalk.Submatrix;

public class OdnoklassnikiUserTrackSubmatrix extends Submatrix {

	private static final String USER_ID = "user_id";
	private static final String TRACK_ID = "track_id";
	
	public OdnoklassnikiUserTrackSubmatrix() throws ClassNotFoundException, SQLException {
		super();
	}
	
	@Override
	public String getColumnFieldName() {
		return TRACK_ID;
	}

	@Override
	public String getOrderFieldName() {
		return OdnoklassnikiDataset.ID_ATTRIBUTE;
	}

	@Override
	public String getRowFieldName() {
		return USER_ID;
	}

	@Override
	public int getSubmatrixSize() {
		ExperimentParameters parameters = ExperimentParameters.getInstance();		
		Dataset datasetProperties = parameters.getDatasetProperties();
		return datasetProperties.getUserTrackCount();
	}

	@Override
	public double[] getSubmatrixValues(int[] trackIds) {
		double[] playCounts = new double[trackIds.length];
		try {
			ExperimentParameters parameters = ExperimentParameters.getInstance();
			DatabaseDataset datasetDatabase = parameters.getDatasetDatabase();
			
			Class.forName(datasetDatabase.getJdbcDriverName());

	        Connection con =
	                DriverManager.getConnection(
	                		datasetDatabase.getJdbcConnectionUrl(),
	                		datasetDatabase.getDatabaseUser(), 
	                		datasetDatabase.getPassword());

			Statement stmt = con.createStatement();
			String query = "select play_count from dbo.user_track order by id";
			ResultSet rs = stmt.executeQuery(query);

			int rowNumber = 0;
			while (rs.next()) {
				playCounts[rowNumber] = rs.getDouble(1);
				rowNumber++;
			}
			rs.close();
			con.close();
		} catch (ClassNotFoundException e) {
			System.out.println("Cannot register JDBC driver");
			e.getMessage();
		} catch (SQLException e) {
			System.out.println("Cannot retrieve data from database");
			e.getMessage();
		}
		return playCounts;
	}

	@Override
	public String getTableName() {
		return OdnoklassnikiDataset.USER_TRACK_TABLE_NAME;
	}

}
